# -*- coding = utf-8 -*-
# @Time：2022/3/11 20:05
# @Author：3ic
# @File：window_options.py.py
# @Software：PyCharm

import sys
import time

import numpy as np
import win32api
import win32con
import win32gui
import win32process
from PyQt5.QtWidgets import QApplication


def getCaptureScreen(ip_class_name, ip_window_name):
    hwnd = win32gui.FindWindow(ip_class_name, ip_window_name)
    app = QApplication(sys.argv)
    screen = QApplication.primaryScreen()
    return hwnd, app, screen


def getOptionScreen(hwnd_, ret_list):
    s = win32gui.GetWindowText(hwnd_)
    if len(s) > 3:
        ret_list.append(hwnd_)
    return 1


# 准备要使用的窗口句柄，默认是雷电模拟器
cap_hwnd, app, screen = getCaptureScreen('LDPlayerMainFrame', '雷电模拟器')
opt_hwnd = []
win32gui.EnumChildWindows(cap_hwnd, getOptionScreen, opt_hwnd)
opt_hwnd = opt_hwnd[0]


def setForegroundWindowByWin32GUI(hwnd):
    hForeWnd = win32gui.GetForegroundWindow()
    FormThreadID = win32api.GetCurrentThreadId()
    CWndThreadID = win32process.GetWindowThreadProcessId(hForeWnd)
    win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, True)
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    win32gui.SetForegroundWindow(hwnd)
    win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, False)


def fastCapture(screen, hwnd, x, y, w, h):
    img = screen.grabWindow(hwnd, x, y, w, h).toImage()
    ptr = img.constBits()
    ptr.setsize(img.byteCount())
    return np.array(ptr).reshape(img.height(), img.width(), 4)


def winPressKey(opt_hwnd, key, times=1, interval=0.01):
    key = ord(key)
    while times > 1:
        times -= 1
        win32gui.SendMessage(opt_hwnd, win32con.WM_KEYDOWN, key, 0)
        win32gui.SendMessage(opt_hwnd, win32con.WM_KEYUP, key, 0)
        time.sleep(interval)
    win32gui.SendMessage(opt_hwnd, win32con.WM_KEYDOWN, key, 0)
    win32gui.SendMessage(opt_hwnd, win32con.WM_KEYUP, key, 0)


def winClickMouse(opt_hwnd, x, y):
    winx1, winy1, winx2, winy2 = win32gui.GetWindowRect(cap_hwnd)
    x = winx1+x*(winx2-winx1)//1920
    y = winy1+y*(winy2-winy1)//1030
    client_pos = win32gui.ScreenToClient(opt_hwnd, (x, y))
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(opt_hwnd, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32api.SendMessage(opt_hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32api.SendMessage(opt_hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)
